#!/usr/bin/env python
# -*- coding: utf-8 -*-
"""
__title__ = ''
__author__ = 'HaiFeng'
__mtime__ = '2016/8/16'
"""
import talib

from py_at.Enums import *
from py_at.strategy import Strategy
from py_at.Data import Data
from py_at.Bar import Bar
import time

class JinKenNa(Strategy):
    def __init__(self,cfg):
        super().__init__(cfg)
        #初始化参数
        if cfg=="":
            self.Params['avgLen'] = 40
            self.Params['atrLen'] = 40
            self.Params['Lots'] = 1
            self.Params['Slippage'] = 1
        self.timeD = ''


    def OnBarUpdate(self, data=Data, bar=Bar):

        # print('时间{0}收盘价格{1}总k线数据'.format(self.D, self.C, len(self.C)))
        # if len(self.C) == 1:       # 第一根bar
        #     self.UpdateParams()

        if len(self.C) < self.Params['avgLen']:     # 如果bar数目小于 p._ma2参数  退出
            return

        # ma1 = talib.MA(self.C, self.p_ma1)
        # ma2 = talib.MA(self.C, self.p_ma2)
        #three line avg

        atr = talib.ATR(self.H, self.L, self.C, timeperiod=self.Params['atrLen'])
        movAvgVal = talib.SMA((self.H + self.L+self.C) / 3, self.Params['avgLen'])
        #upline
        upBand = movAvgVal + 2*atr
        #out
        liquidPoint=movAvgVal
        #dowline
        dnBand = movAvgVal - 2*atr


        if(self.timeD!=self.D[-1]):
            self.Varlist['movAvgVal'] = movAvgVal.tolist()
            self.Varlist['unBand'] = upBand.tolist()
            self.Varlist['dowline']=dnBand.tolist()
            self.timeD = self.D[-1]
        if self.PositionLong==0 and self.PositionShort==0:
            if movAvgVal[-1]>=movAvgVal[-2] and self.H[-1]>=upBand[-1]:
                self.Buy(upBand[-1],self.Params['Lots'],'买开')

            if movAvgVal[-1]<movAvgVal[-2] and self.L[-1]<=dnBand[-1]:
                self.SellShort(dnBand[-1],self.Params['Lots'],'卖开')
        if self.PositionLong >0 and self.L[-1]<=liquidPoint[-1]:
            self.Sell(liquidPoint[-1],self.Params['Lots'],'卖平')
        if self.PositionShort>0 and self.H[-1]>=liquidPoint[-1]:
            self.BuyToCover(liquidPoint[-1],self.Params['Lots'],'买平')



